import { PrismaService } from '../prisma/prisma.service';
import { ConfigService } from '@nestjs/config';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { BadRequestException, Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(configService: ConfigService, private prisma: PrismaService) {
    super({
      //解析用户提交的header中的Bearer Token数据
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      //加密码的 secret
      secretOrKey: process.env.TOKEN_SECRET,
    });
  }

  //验证通过后获取用户资料
  async validate({ sub: id }) {
    const user = this.prisma.user.findUnique({
      where: { id },
    });
    if (!user) {
      throw new BadRequestException('抱歉,你并不是管理员,无法做到删除的功能');
    }
    return user;
  }
}
